<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.9: http://docutils.sourceforge.net/" />
<title>PyShp</title>
<meta name="author" content="Joel Lawhead - jlawhead&#64;geospatialpython.com" />
<style type="text/css">

/*
:Authors: Ian Bicking, Michael Foord
:Contact: fuzzyman@voidspace.org.uk
:Date: 2005/08/26 
:Version: 0.1.0
:Copyright: This stylesheet has been placed in the public domain.

Stylesheet for Docutils.
Based on ``blue_box.css`` by Ian Bicking
and ``html4css1.css`` revision 1.46.
*/

@import url(html4css1.css);

body {
  font-family: Arial, sans-serif;
}

em, i {
  /* Typically serif fonts have much nicer italics */
  font-family: Times New Roman, Times, serif;
}

a.target {
  color: blue;
}

a.target {
  color: blue;
}

a.toc-backref {
  text-decoration: none;
  color: black;
}

a.toc-backref:hover {
  background-color: inherit;
}

a:hover {
  background-color: #cccccc;
}

div.attention, div.caution, div.danger, div.error, div.hint,
div.important, div.note, div.tip, div.warning {
  background-color: #cccccc;
  padding: 3px;
  width: 80%;
}

div.admonition p.admonition-title, div.hint p.admonition-title,
div.important p.admonition-title, div.note p.admonition-title,
div.tip p.admonition-title  {
  text-align: center;
  background-color: #999999;
  display: block;
  margin: 0;
}

div.attention p.admonition-title, div.caution p.admonition-title,
div.danger p.admonition-title, div.error p.admonition-title,
div.warning p.admonition-title {
  color: #cc0000;
  font-family: sans-serif;
  text-align: center;
  background-color: #999999;
  display: block;
  margin: 0;
}

h1, h2, h3, h4, h5, h6 {
  font-family: Helvetica, Arial, sans-serif;
  border: thin solid black;
  /* This makes the borders rounded on Mozilla, which pleases me */
  -moz-border-radius: 8px;
  padding: 4px;
}

h1 {
  background-color: #444499;
  color: #ffffff;
  border: medium solid black;
}

h1 a.toc-backref, h2 a.toc-backref { 
  color: #ffffff;
}

h2 {
  background-color: #666666;
  color: #ffffff;
  border: medium solid black;
}

h3, h4, h5, h6 {
  background-color: #cccccc;
  color: #000000;
}

h3 a.toc-backref, h4 a.toc-backref, h5 a.toc-backref, 
h6 a.toc-backref { 
  color: #000000;
}

h1.title {
  text-align: center;
  background-color: #444499;
  color: #eeeeee;
  border: thick solid black;
  -moz-border-radius: 20px;
}

table.footnote {
  padding-left: 0.5ex;
}

table.citation {
  padding-left: 0.5ex
}

pre.literal-block, pre.doctest-block {
  border: thin black solid;
  padding: 5px;
}

.image img { border-style : solid;
            border-width : 2px;
}

h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt {
  font-size: 100%;
}

code, tt {
  color: #000066;
}


</style>
</head>
<body>
<div class="document" id="pyshp">
<h1 class="title">PyShp</h1>
<table class="docinfo" frame="void" rules="none">
<col class="docinfo-name" />
<col class="docinfo-content" />
<tbody valign="top">
<tr><th class="docinfo-name">Author:</th>
<td>Joel Lawhead - <a class="last reference external" href="mailto:jlawhead&#64;geospatialpython.com">jlawhead&#64;geospatialpython.com</a></td></tr>
</tbody>
</table>
<p>:Version 1.2.0</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">Revised:</th><td class="field-body">September 5, 2013</td>
</tr>
</tbody>
</table>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#overview" id="id1">Overview</a></li>
<li><a class="reference internal" href="#examples" id="id2">Examples</a><ul>
<li><a class="reference internal" href="#reading-shapefiles" id="id3">Reading Shapefiles</a><ul>
<li><a class="reference internal" href="#reading-shapefiles-from-file-like-objects" id="id4">Reading Shapefiles from File-Like Objects</a></li>
<li><a class="reference internal" href="#reading-geometry" id="id5">Reading Geometry</a></li>
<li><a class="reference internal" href="#reading-records" id="id6">Reading Records</a></li>
<li><a class="reference internal" href="#reading-geometry-and-records-simultaneously" id="id7">Reading Geometry and Records Simultaneously</a></li>
</ul>
</li>
<li><a class="reference internal" href="#writing-shapefiles" id="id8">Writing Shapefiles</a><ul>
<li><a class="reference internal" href="#setting-the-shape-type" id="id9">Setting the Shape Type</a></li>
<li><a class="reference internal" href="#geometry-and-record-balancing" id="id10">Geometry and Record Balancing</a></li>
<li><a class="reference internal" href="#adding-geometry" id="id11">Adding Geometry</a></li>
<li><a class="reference internal" href="#creating-attributes" id="id12">Creating Attributes</a></li>
<li><a class="reference internal" href="#file-names" id="id13">File Names</a></li>
<li><a class="reference internal" href="#saving-to-file-like-objects" id="id14">Saving to File-Like Objects</a></li>
</ul>
</li>
<li><a class="reference internal" href="#editing-shapefiles" id="id15">Editing Shapefiles</a></li>
<li><a class="reference internal" href="#python-geo-interface" id="id16">Python __geo_interface__</a></li>
</ul>
</li>
</ul>
</div>
<div class="section" id="overview">
<h1><a class="toc-backref" href="#id1">Overview</a></h1>
<p>PyShp provides read and write support for the Esri
Shapefile format. The Shapefile format is a popular Geographic Information
System vector data format created by Esri.  For more information about this format
please read the well-written &quot;ESRI Shapefile Technical Description - July 1998&quot;
located at <a class="reference external" href="http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf">http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf</a>.
The Esri document describes the shp and shx file formats.  However a third file
format called dbf is also required.  This format is documented on the web as the
&quot;XBase File Format Description&quot; and is a simple file-based database format created
in the 1960's.  For more on this specification see:
<a class="reference external" href="http://www.clicketyclick.dk/databases/xbase/format/index.html">http://www.clicketyclick.dk/databases/xbase/format/index.html</a></p>
<p>Both the Esri and XBase file-formats are very simple in design and
memory efficient which is part of the reason the shapefile format remains popular
despite the numerous ways to store and exchange GIS data available today.</p>
<p>Pyshp is compatible with Python 2.4-3.x.</p>
<p>This document provides examples for using PyShp to read and write shapefiles.</p>
<p>Currently the sample census blockgroup shapefile referenced in the examples is
only available on the google code project site at <a class="reference external" href="http://code.google.com/p/pyshp">http://code.google.com/p/pyshp</a>.
These examples are straight-forward and you can also easily run them against your
own shapefiles manually with minimal modification. Other examples for specific
topics are continually added to the pyshp wiki on google code and the blog
<a class="reference external" href="http://GeospatialPython.com">http://GeospatialPython.com</a>.</p>
<p>Important: For information about map projections, shapefiles,
and Python please visit: <a class="reference external" href="http://code.google.com/p/pyshp/wiki/MapProjections">http://code.google.com/p/pyshp/wiki/MapProjections</a></p>
<p>I sincerely hope this library eliminates the mundane distraction of simply
reading and writing data, and allows you to focus on the challenging and FUN
part of your geospatial project.</p>
</div>
<div class="section" id="examples">
<h1><a class="toc-backref" href="#id2">Examples</a></h1>
<p>Before doing anything you must import the library.</p>
<pre class="doctest-block">
&gt;&gt;&gt; import shapefile
</pre>
<p>The examples below will use a shapefile created from the U.S. Census Bureau
Blockgroups data set near San Francisco, CA and available in the subversion
repository of the pyshp google code site.</p>
<div class="section" id="reading-shapefiles">
<h2><a class="toc-backref" href="#id3">Reading Shapefiles</a></h2>
<p>To read a shapefile create a new &quot;Reader&quot; object and pass it the name of an
existing shapefile. The shapefile format is acutally a collection of three
files. You specify the base filename of the shapefile or the complete filename
of any of the shapefile component files.</p>
<pre class="doctest-block">
&gt;&gt;&gt; sf = shapefile.Reader(&quot;shapefiles/blockgroups&quot;)
</pre>
<p>OR</p>
<pre class="doctest-block">
&gt;&gt;&gt; sf = shapefile.Reader(&quot;shapefiles/blockgroups.shp&quot;)
</pre>
<p>OR</p>
<pre class="doctest-block">
&gt;&gt;&gt; sf = shapefile.Reader(&quot;shapefiles/blockgroups.dbf&quot;)
</pre>
<p>OR any of the other 5+ formats which are potentially part of a shapefile.
The library does not care about extensions.</p>
<div class="section" id="reading-shapefiles-from-file-like-objects">
<h3><a class="toc-backref" href="#id4">Reading Shapefiles from File-Like Objects</a></h3>
<p>You can also load shapefiles from any Python file-like object using keyword
arguments to specify any of the three files.  This feature is very powerful
and allows you to load shapefiles from a url, from a zip file, serialized
object, or in some cases a database.</p>
<pre class="doctest-block">
&gt;&gt;&gt; myshp = open(&quot;shapefiles/blockgroups.shp&quot;, &quot;rb&quot;)
&gt;&gt;&gt; mydbf = open(&quot;shapefiles/blockgroups.dbf&quot;, &quot;rb&quot;)
&gt;&gt;&gt; r = shapefile.Reader(shp=myshp, dbf=mydbf)
</pre>
<p>Notice in the examples above the shx file is never used.  The shx file is a
very simple fixed-record index for the variable length records in the shp file.
This file is optional for reading.  If it's available pyshp will use the shx file
to access shape records a little faster but will do just fine without it.</p>
</div>
<div class="section" id="reading-geometry">
<h3><a class="toc-backref" href="#id5">Reading Geometry</a></h3>
<p>A shapefile's geometry is the collection of points or shapes made from verticies
and implied arcs representing physical locations.  All types of shapefiles
just store points.  The metadata about the points determine how they are handled by
software.</p>
<p>You can get the a list of the shapefile's geometry by calling the shapes()
method.</p>
<pre class="doctest-block">
&gt;&gt;&gt; shapes = sf.shapes()
</pre>
<p>The shapes method returns a list of Shape objects describing the
geometry of each shape record.</p>
<pre class="doctest-block">
&gt;&gt;&gt; len(shapes)
663
</pre>
<p>You can iterate through the shapefile's geometry using the iterShapes() method.</p>
<pre class="doctest-block">
&gt;&gt;&gt; len(list(sf.iterShapes()))
663
</pre>
<p>Each shape record contains the following attributes:</p>
<pre class="doctest-block">
&gt;&gt;&gt; for name in dir(shapes[3]):
...     if not name.startswith('__'):
...         name
'bbox'
'parts'
'points'
'shapeType'
</pre>
<blockquote>
<ul class="simple">
<li>shapeType: an integer representing the type of shape as defined by the
shapefile specification.</li>
</ul>
</blockquote>
<pre class="doctest-block">
&gt;&gt;&gt; shapes[3].shapeType
5
</pre>
<blockquote>
<ul class="simple">
<li>bbox: If the shape type contains multiple points this tuple describes the
lower left (x,y) coordinate and upper right corner coordinate creating a
complete box around the points. If the shapeType is a Null
(shapeType == 0) then an AttributeError is raised.</li>
</ul>
</blockquote>
<pre class="doctest-block">
&gt;&gt;&gt; # Get the bounding box of the 4th shape.
&gt;&gt;&gt; # Round coordinates to 3 decimal places
&gt;&gt;&gt; bbox = shapes[3].bbox
&gt;&gt;&gt; ['%.3f' % coord for coord in bbox]
['-122.486', '37.787', '-122.446', '37.811']
</pre>
<blockquote>
<ul class="simple">
<li>parts: Parts simply group collections of points into shapes. If the shape record
has multiple parts this attribute contains the index of the first point of each part.
If there is only one part then a list containing 0 is returned.</li>
</ul>
</blockquote>
<pre class="doctest-block">
&gt;&gt;&gt; shapes[3].parts
[0]
</pre>
<blockquote>
<ul class="simple">
<li>points: The points attribute contains a list of tuples containing an (x,y)
coordinate for each point in the shape.</li>
</ul>
</blockquote>
<pre class="doctest-block">
&gt;&gt;&gt; len(shapes[3].points)
173
&gt;&gt;&gt; # Get the 8th point of the fourth shape
&gt;&gt;&gt; # Truncate coordinates to 3 decimal places
&gt;&gt;&gt; shape = shapes[3].points[7]
&gt;&gt;&gt; ['%.3f' % coord for coord in shape]
['-122.471', '37.787']
</pre>
<p>To read a single shape by calling its index use the shape() method. The index
is the shape's count from 0. So to read the 8th shape record you would
use its index which is 7.</p>
<pre class="doctest-block">
&gt;&gt;&gt; s = sf.shape(7)
</pre>
<pre class="doctest-block">
&gt;&gt;&gt; # Read the bbox of the 8th shape to verify
&gt;&gt;&gt; # Round coordinates to 3 decimal places
&gt;&gt;&gt; ['%.3f' % coord for coord in s.bbox]
['-122.450', '37.801', '-122.442', '37.808']
</pre>
</div>
<div class="section" id="reading-records">
<h3><a class="toc-backref" href="#id6">Reading Records</a></h3>
<p>A record in a shapefile contains the attributes for each shape in the
collection of geometry. Records are stored in the dbf file. The link
between geometry and attributes is the foundation of Geographic Information
Systems. This critical link is implied by the order of shapes and
corresponding records in the shp geometry file and the dbf attribute file.</p>
<p>The field names of a shapefile are available as soon as you read a shapefile.
You can call the &quot;fields&quot; attribute of the shapefile as a Python list. Each
field is a Python list with the following information:</p>
<ul class="simple">
<li>Field name: the name describing the data at this column index.</li>
<li>Field type: the type of data at this column index. Types can be: Character, Numbers, Longs, Dates, or Memo.
The &quot;Memo&quot; type has no meaning within a GIS and is part of the xbase spec instead.</li>
<li>Field length: the length of the data found at this column index.  Older GIS software may truncate this
length to 8 or 11 characters for &quot;Character&quot; fields.</li>
<li>Decimal length: the number of decimal places found in &quot;Number&quot; fields.</li>
</ul>
<p>To see the fields for the Reader object above (sf) call the &quot;fields&quot; attribute:</p>
<pre class="doctest-block">
&gt;&gt;&gt; fields = sf.fields
</pre>
<pre class="doctest-block">
&gt;&gt;&gt; assert fields == [(&quot;DeletionFlag&quot;, &quot;C&quot;, 1, 0), [&quot;AREA&quot;, &quot;N&quot;, 18, 5],
... [&quot;BKG_KEY&quot;, &quot;C&quot;, 12, 0], [&quot;POP1990&quot;, &quot;N&quot;, 9, 0], [&quot;POP90_SQMI&quot;, &quot;N&quot;, 10, 1],
... [&quot;HOUSEHOLDS&quot;, &quot;N&quot;, 9, 0],
... [&quot;MALES&quot;, &quot;N&quot;, 9, 0], [&quot;FEMALES&quot;, &quot;N&quot;, 9, 0], [&quot;WHITE&quot;, &quot;N&quot;, 9, 0],
... [&quot;BLACK&quot;, &quot;N&quot;, 8, 0], [&quot;AMERI_ES&quot;, &quot;N&quot;, 7, 0], [&quot;ASIAN_PI&quot;, &quot;N&quot;, 8, 0],
... [&quot;OTHER&quot;, &quot;N&quot;, 8, 0], [&quot;HISPANIC&quot;, &quot;N&quot;, 8, 0], [&quot;AGE_UNDER5&quot;, &quot;N&quot;, 8, 0],
... [&quot;AGE_5_17&quot;, &quot;N&quot;, 8, 0], [&quot;AGE_18_29&quot;, &quot;N&quot;, 8, 0], [&quot;AGE_30_49&quot;, &quot;N&quot;, 8, 0],
... [&quot;AGE_50_64&quot;, &quot;N&quot;, 8, 0], [&quot;AGE_65_UP&quot;, &quot;N&quot;, 8, 0],
... [&quot;NEVERMARRY&quot;, &quot;N&quot;, 8, 0], [&quot;MARRIED&quot;, &quot;N&quot;, 9, 0], [&quot;SEPARATED&quot;, &quot;N&quot;, 7, 0],
... [&quot;WIDOWED&quot;, &quot;N&quot;, 8, 0], [&quot;DIVORCED&quot;, &quot;N&quot;, 8, 0], [&quot;HSEHLD_1_M&quot;, &quot;N&quot;, 8, 0],
... [&quot;HSEHLD_1_F&quot;, &quot;N&quot;, 8, 0], [&quot;MARHH_CHD&quot;, &quot;N&quot;, 8, 0],
... [&quot;MARHH_NO_C&quot;, &quot;N&quot;, 8, 0], [&quot;MHH_CHILD&quot;, &quot;N&quot;, 7, 0],
... [&quot;FHH_CHILD&quot;, &quot;N&quot;, 7, 0], [&quot;HSE_UNITS&quot;, &quot;N&quot;, 9, 0], [&quot;VACANT&quot;, &quot;N&quot;, 7, 0],
... [&quot;OWNER_OCC&quot;, &quot;N&quot;, 8, 0], [&quot;RENTER_OCC&quot;, &quot;N&quot;, 8, 0],
... [&quot;MEDIAN_VAL&quot;, &quot;N&quot;, 7, 0], [&quot;MEDIANRENT&quot;, &quot;N&quot;, 4, 0],
... [&quot;UNITS_1DET&quot;, &quot;N&quot;, 8, 0], [&quot;UNITS_1ATT&quot;, &quot;N&quot;, 7, 0], [&quot;UNITS2&quot;, &quot;N&quot;, 7, 0],
... [&quot;UNITS3_9&quot;, &quot;N&quot;, 8, 0], [&quot;UNITS10_49&quot;, &quot;N&quot;, 8, 0],
... [&quot;UNITS50_UP&quot;, &quot;N&quot;, 8, 0], [&quot;MOBILEHOME&quot;, &quot;N&quot;, 7, 0]]
</pre>
<p>You can get a list of the shapefile's records by calling the records() method:</p>
<pre class="doctest-block">
&gt;&gt;&gt; records = sf.records()
</pre>
<pre class="doctest-block">
&gt;&gt;&gt; len(records)
663
</pre>
<p>Similar to the geometry methods, you can iterate through dbf records using the
recordsIter() method.</p>
<pre class="doctest-block">
&gt;&gt;&gt; len(list(sf.iterRecords()))
663
</pre>
<p>Each record is a list containing an attribute corresponding to each field in the
field list.</p>
<p>For example in the 4th record of the blockgroups shapefile the 2nd and 3rd
fields are the blockgroup id and the 1990 population count of
that San Francisco blockgroup:</p>
<pre class="doctest-block">
&gt;&gt;&gt; records[3][1:3]
['060750601001', 4715]
</pre>
<p>To read a single record call the record() method with the record's index:</p>
<pre class="doctest-block">
&gt;&gt;&gt; rec = sf.record(3)
</pre>
<pre class="doctest-block">
&gt;&gt;&gt; rec[1:3]
['060750601001', 4715]
</pre>
</div>
<div class="section" id="reading-geometry-and-records-simultaneously">
<h3><a class="toc-backref" href="#id7">Reading Geometry and Records Simultaneously</a></h3>
<p>You way want to examine both the geometry and the attributes for a record at the
same time. The shapeRecord() and shapeRecords() method let you do just that.</p>
<p>Calling the shapeRecords() method will return the geometry and attributes for
all shapes as a list of ShapeRecord objects. Each ShapeRecord instance has a
&quot;shape&quot; and &quot;record&quot; attribute. The shape attribute is a ShapeRecord object as
dicussed in the first section &quot;Reading Geometry&quot;. The record attribute is a
list of field values as demonstrated in the &quot;Reading Records&quot; section.</p>
<pre class="doctest-block">
&gt;&gt;&gt; shapeRecs = sf.shapeRecords()
</pre>
<p>Let's read the blockgroup key and the population for the 4th blockgroup:
&gt;&gt;&gt; shapeRecs[3].record[1:3]
['060750601001', 4715]</p>
<p>Now let's read the first two points for that same record:</p>
<pre class="doctest-block">
&gt;&gt;&gt; points = shapeRecs[3].shape.points[0:2]
</pre>
<pre class="doctest-block">
&gt;&gt;&gt; len(points)
2
</pre>
<p>The shapeRec() method reads a single shape/record pair at the specified index.
To get the 4th shape record from the blockgroups shapfile use the third index:</p>
<pre class="doctest-block">
&gt;&gt;&gt; shapeRec = sf.shapeRecord(3)
</pre>
<p>The blockgroup key and population count:</p>
<pre class="doctest-block">
&gt;&gt;&gt; shapeRec.record[1:3]
['060750601001', 4715]
</pre>
<pre class="doctest-block">
&gt;&gt;&gt; points = shapeRec.shape.points[0:2]
</pre>
<pre class="doctest-block">
&gt;&gt;&gt; len(points)
2
</pre>
</div>
</div>
<div class="section" id="writing-shapefiles">
<h2><a class="toc-backref" href="#id8">Writing Shapefiles</a></h2>
<p>PyShp tries to be as flexible as possible when writing shapefiles while
maintaining some degree of automatic validation to make sure you don't
accidentally write an invalid file.</p>
<p>PyShp can write just one of the component files such as the shp or dbf file
without writing the others. So in addition to being a complete
shapefile library, it can also be used as a basic dbf (xbase) library. Dbf files are
a common database format which are often useful as a standalone simple
database format. And even shp files occasionaly have uses as a standalone
format. Some web-based GIS systems use an user-uploaded shp file to specify
an area of interest. Many precision agriculture chemical field sprayers also
use the shp format as a control file for the sprayer system (usually in
combination with custom database file formats).</p>
<p>To create a shapefile you add geometry and/or attributes using methods in the
Writer class until you are ready to save the file.</p>
<p>Create an instance of the Writer class to begin creating a shapefile:</p>
<pre class="doctest-block">
&gt;&gt;&gt; w = shapefile.Writer()
</pre>
<div class="section" id="setting-the-shape-type">
<h3><a class="toc-backref" href="#id9">Setting the Shape Type</a></h3>
<p>The shape type defines the type of geometry contained in the shapefile. All of
the shapes must match the shape type setting.</p>
<p>Shape types are represented by numbers between 0 and 31 as defined by the
shapefile specification. It is important to note that numbering system has
several reserved numbers which have not been used yet therefore the numbers of
the existing shape types are not sequential.</p>
<p>You can reference shape types by the numbers or by constants defined by PyShp:
shapefile.NULL = 0
shapefile.POINT = 1
shapefile.POLYLINE = 3
shapefile.POLYGON = 5
shapefile.MULTIPOINT = 8
shapefile.POINTZ = 11
shapefile.POLYLINEZ = 13
shapefile.POLYGONZ = 15
shapefile.MULTIPOINTZ = 18
shapefile.POINTM = 21
shapefile.POLYLINEM = 23
shapefile.POLYGONM = 25
shapefile.MULTIPOINTM = 28
shapefile.MULTIPATCH = 31</p>
<p>There are three ways to set the shape type:
- Set it when creating the class instance.
- Set it by assigning a value to an existing class instance.
- Set it automatically to the type of the first shape by saving the shapefile.</p>
<p>To manually set the shape type for a Writer object when creating the Writer:</p>
<pre class="doctest-block">
&gt;&gt;&gt; w = shapefile.Writer(shapeType=1)
</pre>
<p>or we can use the constants as explained above:</p>
<pre class="doctest-block">
&gt;&gt;&gt; w = shapefile.Writer(shapefile.POINT)
</pre>
<p>As you can see, specifying the shapeType argument explicitly isn't necessary.</p>
<pre class="doctest-block">
&gt;&gt;&gt; w.shapeType
1
</pre>
<p>OR you can set it after the Writer is created by changing the property:</p>
<pre class="doctest-block">
&gt;&gt;&gt; w.shapeType = 3
</pre>
<pre class="doctest-block">
&gt;&gt;&gt; w.shapeType
3
</pre>
</div>
<div class="section" id="geometry-and-record-balancing">
<h3><a class="toc-backref" href="#id10">Geometry and Record Balancing</a></h3>
<p>Because every shape must have a corresponding record it is critical that the
number of records equals the number of shapes to create a valid shapefile. To
help prevent accidental misalignment PyShp has an &quot;auto balance&quot; feature to
make sure when you add either a shape or a record the two sides of the
equation line up. This feature is NOT turned on by default. To activate it
set the attribute autoBalance to 1 (True):</p>
<pre class="doctest-block">
&gt;&gt;&gt; w.autoBalance = 1
</pre>
<p>You also have the option of manually calling the balance() method each time you
add a shape or a record to ensure the other side is up to date.  When balancing
is used null shapes are created on the geometry side or a record with a value of
&quot;NULL&quot; for each field is created on the attribute side.</p>
<p>The balancing option gives you flexibility in how you build the shapefile.</p>
<p>Without auto balancing you can add geometry or records at anytime. You can
create all of the shapes and then create all of the records or vice versa. You
can use the balance method after creating a shape or record each time and make
updates later. If you do not use the balance method and forget to manually
balance the geometry and attributes the shapefile will be viewed as corrupt by
most shapefile software.</p>
<p>With auto balanacing you can add either shapes or geometry and update blank
entries on either side as needed. Even if you forget to update an entry the
shapefile will still be valid and handled correctly by most shapefile software.</p>
</div>
<div class="section" id="adding-geometry">
<h3><a class="toc-backref" href="#id11">Adding Geometry</a></h3>
<p>Geometry is added using one of three methods: &quot;null&quot;, &quot;point&quot;, or &quot;poly&quot;. The &quot;null&quot;
method is used for null shapes, &quot;point&quot; is used for point shapes, and &quot;poly&quot; is
used for everything else.</p>
<p><strong>Adding a Null shape</strong></p>
<p>Because Null shape types (shape type 0) have no geometry the &quot;null&quot; method is
called without any arguments.</p>
<pre class="doctest-block">
&gt;&gt;&gt; w = shapefile.Writer()
</pre>
<pre class="doctest-block">
&gt;&gt;&gt; w.null()
</pre>
<p>The writer object's shapes list will now have one null shape:</p>
<pre class="doctest-block">
&gt;&gt;&gt; assert w.shapes()[0].shapeType == shapefile.NULL
</pre>
<p><strong>Adding a Point shape</strong></p>
<p>Point shapes are added using the &quot;point&quot; method. A point is specified by an
x, y, and optional z (elevation) and m (measure) value.</p>
<pre class="doctest-block">
&gt;&gt;&gt; w = shapefile.Writer(shapefile.POINT)
</pre>
<pre class="doctest-block">
&gt;&gt;&gt; w.point(122, 37) # No elevation or measure values
</pre>
<pre class="doctest-block">
&gt;&gt;&gt; w.shapes()[0].points
[[122, 37, 0, 0]]
</pre>
<pre class="doctest-block">
&gt;&gt;&gt; w.point(118, 36, 4, 8)
</pre>
<pre class="doctest-block">
&gt;&gt;&gt; w.shapes()[1].points
[[118, 36, 4, 8]]
</pre>
<p><strong>Adding a Poly Shape</strong></p>
<p>&quot;Poly&quot; shapes can be either polygons or lines.  Shapefile polygons must have at
least 4 points and the last point must be the same as the first. PyShp automatically
enforces closed polygons.
A line must have at least two points.
Because of the similarities between these two shape types they are created using
a single method called &quot;poly&quot;.</p>
<pre class="doctest-block">
&gt;&gt;&gt; w = shapefile.Writer(shapefile.POLYGON)
</pre>
<pre class="doctest-block">
&gt;&gt;&gt; w.poly(shapeType=3, parts=[[[122,37,4,9], [117,36,3,4]], [[115,32,8,8],
... [118,20,6,4], [113,24]]])
</pre>
<p><strong>Adding a Polygon with Rings</strong></p>
<p>Polygons consist of rings which mean they are closed.  The first point and last point
of a ring must be the same. PyShp enforces ring closure if the ring is incomplete when
you add the shape.  Polygons can have inner rings which create holes.  Holes are defined
by the order of the points.  Normally points in a ring run clockwise.  If the points
run counter-clockwise then they form a hole.  If you don't order the points correctly
you'll just have overlapping polygons.</p>
<pre class="doctest-block">
&gt;&gt;&gt; w = shapefile.Writer(shapefile.POLYGON)
&gt;&gt;&gt; outer_ring = [[10,10],[50,50],[100,10],[50,-50],[10,10]]
&gt;&gt;&gt; inner_ring = [[40,10],[50,30],[70,10],[50,-30],[40,10]]
&gt;&gt;&gt; inner_ring.reverse()
</pre>
<p>You can use the &quot;shapefile.signed_area()&quot; method to determine if a ring is clockwise
or counter-clockwise.  A value &gt;= 0 means the ring is counter-clockwise and &lt; 0 means
the ring is clockwise.  The value returned is also the area of the polygon.</p>
<pre class="doctest-block">
&gt;&gt;&gt; # Clockwise ring
... shapefile.signed_area(outer_ring)
-4500.0
&gt;&gt;&gt; # Counter-clockwise ring
... shapefile.signed_area(inner_ring)
900.0
</pre>
<p><strong>Creating 3D Polygons</strong></p>
<p>Elevation values, known as &quot;Z&quot; values allow you to create 3-dimensional shapefiles. The
z value is an extra value specified as part of a point.</p>
<pre class="doctest-block">
&gt;&gt;&gt; w = shapefile.Writer(shapeType=shapefile.POLYGONZ)
&gt;&gt;&gt; w.poly([[[-89.0, 33, 12], [-90, 31, 11], [-91, 30, 12]]], shapeType=15)
&gt;&gt;&gt; w.field(&quot;NAME&quot;)
&gt;&gt;&gt; w.record(&quot;PolyZTest&quot;)
&gt;&gt;&gt; w.save(&quot;shapefiles/test/MyPolyZ&quot;)
</pre>
<p>The z values are stored in a seperate shape attribute.</p>
<pre class="doctest-block">
&gt;&gt;&gt; r = shapefile.Reader(&quot;shapefiles/test/MyPolyZ&quot;)
&gt;&gt;&gt; s = r.shape(0)
&gt;&gt;&gt; s.points
[[-89.0, 33.0], [-90.0, 31.0], [-91.0, 30.0], [-89.0, 33.0]]
&gt;&gt;&gt; s.z
[12.0, 11.0, 12.0, 12.0]
</pre>
</div>
<div class="section" id="creating-attributes">
<h3><a class="toc-backref" href="#id12">Creating Attributes</a></h3>
<p>Creating attributes involves two steps. Step 1 is to create fields to contain
attribute values and step 2 is to populate the fields with values for each
shape record.</p>
<p>The following attempts to create a complete shapefile:</p>
<pre class="doctest-block">
&gt;&gt;&gt; w = shapefile.Writer(shapefile.POINT)
&gt;&gt;&gt; w.point(1,1)
&gt;&gt;&gt; w.point(3,1)
&gt;&gt;&gt; w.point(4,3)
&gt;&gt;&gt; w.point(2,2)
&gt;&gt;&gt; w.field('FIRST_FLD')
&gt;&gt;&gt; w.field('SECOND_FLD','C','40')
&gt;&gt;&gt; w.record('First','Point')
&gt;&gt;&gt; w.record('Second','Point')
&gt;&gt;&gt; w.record('Third','Point')
&gt;&gt;&gt; w.record('Fourth','Point')
&gt;&gt;&gt; w.save('shapefiles/test/point')
</pre>
<pre class="doctest-block">
&gt;&gt;&gt; w = shapefile.Writer(shapefile.POLYGON)
&gt;&gt;&gt; w.poly(parts=[[[1,5],[5,5],[5,1],[3,3],[1,1]]])
&gt;&gt;&gt; w.field('FIRST_FLD','C','40')
&gt;&gt;&gt; w.field('SECOND_FLD','C','40')
&gt;&gt;&gt; w.record('First','Polygon')
&gt;&gt;&gt; w.save('shapefiles/test/polygon')
</pre>
<pre class="doctest-block">
&gt;&gt;&gt; w = shapefile.Writer(shapefile.POLYLINE)
&gt;&gt;&gt; w.line(parts=[[[1,5],[5,5],[5,1],[3,3],[1,1]]])
&gt;&gt;&gt; w.poly(parts=[[[1,3],[5,3]]], shapeType=shapefile.POLYLINE)
&gt;&gt;&gt; w.field('FIRST_FLD','C','40')
&gt;&gt;&gt; w.field('SECOND_FLD','C','40')
&gt;&gt;&gt; w.record('First','Line')
&gt;&gt;&gt; w.record('Second','Line')
&gt;&gt;&gt; w.save('shapefiles/test/line')
</pre>
<p>You can also add attributes using keyword arguments where the keys are field names.</p>
<pre class="doctest-block">
&gt;&gt;&gt; w = shapefile.Writer(shapefile.POLYLINE)
&gt;&gt;&gt; w.line(parts=[[[1,5],[5,5],[5,1],[3,3],[1,1]]])
&gt;&gt;&gt; w.field('FIRST_FLD','C','40')
&gt;&gt;&gt; w.field('SECOND_FLD','C','40')
&gt;&gt;&gt; w.record(FIRST_FLD='First', SECOND_FLD='Line')
&gt;&gt;&gt; w.save('shapefiles/test/line')
</pre>
</div>
<div class="section" id="file-names">
<h3><a class="toc-backref" href="#id13">File Names</a></h3>
<p>File extensions are optional when reading or writing shapfiles.  If you specify them Pyshp
ignores them anyway. When you save files you can specify a base file name that is used for
all three file types.  Or you can specify a nmae for one or more file types.  In that case,
any file types not assigned will not save and only file types with file names will be saved.
If you do not specify any file names (i.e. save()), then a unique file name is generated with
the prefix &quot;shapefile_&quot; followed by random characters which is used for all three files.  The
unique file name is returned as a string.</p>
<pre class="doctest-block">
&gt;&gt;&gt; targetName = w.save()
&gt;&gt;&gt; assert(&quot;shapefile_&quot; in targetName)
</pre>
</div>
<div class="section" id="saving-to-file-like-objects">
<h3><a class="toc-backref" href="#id14">Saving to File-Like Objects</a></h3>
<p>Just as you can read shapefiles from python file-like objects you can also write them.</p>
<pre class="doctest-block">
&gt;&gt;&gt; try:
...     from StringIO import StringIO
... except ImportError:
...     from io import BytesIO as StringIO
&gt;&gt;&gt; shp = StringIO()
&gt;&gt;&gt; shx = StringIO()
&gt;&gt;&gt; dbf = StringIO()
&gt;&gt;&gt; w.saveShp(shp)
&gt;&gt;&gt; w.saveShx(shx)
&gt;&gt;&gt; w.saveDbf(dbf)
&gt;&gt;&gt; # Normally you would call the &quot;StringIO.getvalue()&quot; method on these objects.
&gt;&gt;&gt; shp = shx = dbf = None
</pre>
</div>
</div>
<div class="section" id="editing-shapefiles">
<h2><a class="toc-backref" href="#id15">Editing Shapefiles</a></h2>
<p>The Editor class attempts to make changing existing shapefiles easier by handling the reading and writing details behind the scenes.</p>
<p>Let's add shapes to existing shapefiles:</p>
<p>Add a point to a point shapefile</p>
<pre class="doctest-block">
&gt;&gt;&gt; e = shapefile.Editor(shapefile=&quot;shapefiles/test/point.shp&quot;)
&gt;&gt;&gt; e.point(0,0,10,2)
&gt;&gt;&gt; e.record(&quot;Appended&quot;,&quot;Point&quot;)
&gt;&gt;&gt; # We added z and m values so
&gt;&gt;&gt; # change the shapetype
&gt;&gt;&gt; e.shapeType = shapefile.POINTZ
&gt;&gt;&gt; e.save('shapefiles/test/point')
</pre>
<p>Edit the appended point to change the &quot;y&quot; and &quot;z&quot; value</p>
<pre class="doctest-block">
&gt;&gt;&gt; e = shapefile.Editor(shapefile=&quot;shapefiles/test/point.shp&quot;)
&gt;&gt;&gt;     # Find the point by the attribute
&gt;&gt;&gt; for s in enumerate(e.records):
...     i, record = s
...     if record[0] == &quot;Appended&quot;:
...         geom = e._shapes[i]
...         # Change the y value to 5
...         geom.points[0][1] = 5
...         # Change the z value to 9
...         if hasattr(geom, &quot;z&quot;):
...                 geom.z = (9,)
...         else:
...             geom.points[0][2] = 9
&gt;&gt;&gt; e.save('shapefiles/test/point')
</pre>
<p>Add a new line to a line shapefile:</p>
<pre class="doctest-block">
&gt;&gt;&gt; e = shapefile.Editor(shapefile=&quot;shapefiles/test/line.shp&quot;)
&gt;&gt;&gt; e.line(parts=[[[10,5],[15,5],[15,1],[13,3],[11,1]]])
&gt;&gt;&gt; e.record('Appended','Line')
&gt;&gt;&gt; e.save('shapefiles/test/line')
&gt;&gt;&gt; e = None
</pre>
<p>Add a new polygon to a polygon shapefile:</p>
<pre class="doctest-block">
&gt;&gt;&gt; e = shapefile.Editor(shapefile=&quot;shapefiles/test/polygon.shp&quot;)
&gt;&gt;&gt; e.poly(parts=[[[5.1,5],[9.9,5],[9.9,1],[7.5,3],[5.1,1]]])
&gt;&gt;&gt; e.record(&quot;Appended&quot;,&quot;Polygon&quot;)
&gt;&gt;&gt; e.save('shapefiles/test/polygon')
&gt;&gt;&gt; e = None
</pre>
<p>Remove the first point in each shapefile - for a point shapefile that is
the first shape and record&quot;</p>
<pre class="doctest-block">
&gt;&gt;&gt; e = shapefile.Editor(shapefile=&quot;shapefiles/test/point.shp&quot;)
&gt;&gt;&gt; e.delete(0)
&gt;&gt;&gt; e.save('shapefiles/test/point')
&gt;&gt;&gt; e = None
</pre>
<p>Remove the last shape in the polygon shapefile.</p>
<pre class="doctest-block">
&gt;&gt;&gt; e = shapefile.Editor(shapefile=&quot;shapefiles/test/polygon.shp&quot;)
&gt;&gt;&gt; e.delete(-1)
&gt;&gt;&gt; e.save('shapefiles/test/polygon')
&gt;&gt;&gt; e = None
</pre>
</div>
<div class="section" id="python-geo-interface">
<h2><a class="toc-backref" href="#id16">Python __geo_interface__</a></h2>
<p>The Python __geo_interface__ convention provides a data interchange interface
among geospatial Python libraries.  The interface returns data as GeoJSON.
More information on the __geo_interface__ protocol can be found at:
<a class="reference external" href="https://gist.github.com/sgillies/2217756">https://gist.github.com/sgillies/2217756</a>.
More information on GeoJSON is available at <a class="reference external" href="http://geojson.org">http://geojson.org</a> <a class="reference external" href="http://geojson.org">http://geojson.org</a>.</p>
<pre class="doctest-block">
&gt;&gt;&gt; s = sf.shape(0)
&gt;&gt;&gt; s.__geo_interface__[&quot;type&quot;]
'MultiPolygon'
</pre>
</div>
</div>
</div>
</body>
</html>
